import send_msg from '@feidao/service/send-msg';

interface IQueryParam {
	criteria: object;
	fields: { [field_name: string]: 1 | -1 };
	page_no: number;
	page_size: number;
	query_mode: 1;
	sort: {};
	spaceid: string;
	sql: string;
	systemid: string;
	tablename: string;
}

interface IQueryResult {
	query_mode: 1;
	spaceid: string;
	systemid: string;
	tablename: string;
	dataArray: IBaseTable[];
}

export default function query(action_id: string, session_id: string, spaceid: string, systemid: string) {
	const params = [] as IQueryParam[];

	function prepare(tablename: string, fields: string[], filter: object, page_size = 0, page_no = 1, asc = [] as string[], desc = [] as string[]) {
		const sort = asc.map((field) => {
			return { [field]: 1 };
		}).concat(desc.map((field) => {
			return { [field]: -1 };
		})).reduce((pre, cur) => {
			return { ...pre, ...cur };
		}, {});
		params.push({
			criteria: filter,
			fields: fields.reduce((pre, cur) => {
				pre[cur] = 1;
				return pre;
			}, {}),
			page_no,
			page_size,
			query_mode: 1,
			spaceid,
			sql: '',
			systemid,
			tablename
		} as IQueryParam);
	}

	async function exec() {
		const data = await (send_msg(action_id, session_id, spaceid)('dbacc.find.intranet', params) as Promise<IQueryResult[]>);
		return data.map((d) => {
			return d.dataArray;
		});
	}

	return {
		exec,
		prepare
	};
}
